package org.mars.rover.navigation.utils;

import org.mars.rover.navigation.data.Location;
import org.mars.rover.navigation.exception.NavigationException;

public class Navigator {
	
	private int topx = 0;
	private int topy = 0;
	public Navigator(int topx,int topy){
		this.topx = topx;
		this.topy = topy;
	}
	
	
	/**
	 * 
	 * @param currentOrientation 
	 * @param turnDirection
	 * @return
	 * currentOrienation could be N/E/W/S 
	 * turnDirection will be R/L
	 * 
	 */
	public  final String turnRover(String currentOrientation,String turnDirection){
		String direction = null;
		char current = currentOrientation.charAt(0);
		// Trun Rover and calculate new orientation
			switch(current){
				case NavigationConstants.NORTH_CHAR :
					direction = turnDirection.equalsIgnoreCase(NavigationConstants.LEFT) ? 
								NavigationConstants.WEST : NavigationConstants.EAST ;
					break;
				case NavigationConstants.SOUTH_CHAR :
					direction = turnDirection.equalsIgnoreCase(NavigationConstants.LEFT) ?
								NavigationConstants.EAST : NavigationConstants.WEST ;
					break;
				case NavigationConstants.EAST_CHAR :
					direction = turnDirection.equalsIgnoreCase(NavigationConstants.LEFT) ?
							NavigationConstants.NORTH : NavigationConstants.SOUTH ;					
					break;
				case NavigationConstants.WEST_CHAR :
					direction = turnDirection.equalsIgnoreCase(NavigationConstants.LEFT) ?
							NavigationConstants.SOUTH : NavigationConstants.NORTH ;					
					
					break;
				default :
					return null ;
					
			}
			
		
		return direction;
	}
	
	/**
	 * 
	 * @param currentLocation
	 * @param direction
	 * @return
	 * currentLocaion could be like {1,1,E}
	 * direction N/E/W/S
	 */
	public  final Location move(Location currentLocation,String direction)throws NavigationException{
		Location location = null;
		char dir = direction.charAt(0);
		int x = currentLocation.getX();
		int y = currentLocation.getY();
		//From current location and new direction calculate new location
		switch(dir){
		case NavigationConstants.NORTH_CHAR :
			//If N y+1
			location = new Location(x, y+1, direction);
			break;
		case NavigationConstants.SOUTH_CHAR :
			//If S y-1
			location = new Location(x, y-1, direction);
			break ;
		case NavigationConstants.EAST_CHAR :
			//if E x+1
			location = new Location(x+1, y, direction);
			break;
		case NavigationConstants.WEST_CHAR :
			//if W x-1
			location = new Location(x-1, y, direction);
			break ;
		default :
			return null ;
		}
		if(location.getX() == -1 || location.getY() == -1 ||
				location.getX() > topx || location.getY() > topy){
			throw new NavigationException("There is some error with movment. Pls check input");
		}
		return location;
	}
	
}
